﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Saisie_des_prélèvements.Models;
using Saisie_des_prélèvements.ViewModels;
using Saisie_des_prélèvements.Common;
using Windows.UI.Xaml.Media;
using Windows.UI;
using Windows.UI.Popups;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Saisie_des_prélèvements.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class TakenSummaryPage : Saisie_des_prélèvements.Common.LayoutAwarePage
    {
        public int CurrentTakenID = 0;
        public string CurrentUser = string.Empty;
        
        private List<TextBox> _TextBoxs = new List<TextBox>();

        public TakenSummaryPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            CurrentTakenID = int.Parse(navigationParameter.ToString());
            TakenViewModel taken = (new TakenViewModel()).GetTakenInfoById(CurrentTakenID);
            
            var db = new SQLite.SQLiteConnection(App.DBPath);
            k_user u = db.Table<k_user>().Where(a => a.user_id == App.CurrentUserId).First();
            CurrentUser = string.Format("{0} {1}", u.user_first_name, u.user_last_name).Trim();
            k_taken t = db.Table<k_taken>().Where(a => a.taken_id == CurrentTakenID).First();
            k_setting set = db.Table<k_setting>().First();

            if (t.sample_number == null || t.sample_number == "")
            {
                t.sample_number = string.Format("{0}{1}{2}{3}{4}", DateTime.Now.ToString("yy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"), App.Marchine, set.taken_seq);
                db.Update(t);
                taken.SampleNumber = t.sample_number;
                set.taken_seq = (int.Parse(set.taken_seq) + 1).ToString("00000");
                db.Update(set);
            }

            txtProductCode.Text = taken.ProductCode.ToString();
            txtProductNo.Text = taken.SampleNumber;
            

            k_client_taken info = db.Table<k_client_taken>().Where(c => c.client_taken_id == taken.ClientTakenId).First();

            txtClientCode.Text = info.client_taken_code;
            txtNoDos.Text = info.client_seq;

            NPRODUITViewModel product = (new NPRODUITViewModel()).GetProductInfo(taken.ProductCode);
            string[] Pro_Tabl = product.PRD_TABL.Split(';');
            

            lbl01.Text = product.PRD_LIBID1;
            lbl02.Text = product.PRD_LIBID2;
            lbl03.Text = product.PRD_LIBID3;
            lbl04.Text = product.PRD_LIBID4;
            lbl05.Text = product.PRD_LIBID5;
            lbl06.Text = product.PRD_LIBID6;
            lbl07.Text = product.PRD_LIBID7;
            lbl08.Text = product.PRD_LIBID8;
            lbl09.Text = product.PRD_LIBID9;
            lbl10.Text = product.PRD_LIBID10;
            lbl11.Text = product.PRD_LIBID11;
            lbl12.Text = product.PRD_LIBID12;

            Visibilitys(1, product.PRD_LIBID1, Pro_Tabl[0], product.PRD_TYPID);
            Visibilitys(2, product.PRD_LIBID2, Pro_Tabl[1], product.PRD_TYPID);
            Visibilitys(3, product.PRD_LIBID3, Pro_Tabl[2], product.PRD_TYPID);
            Visibilitys(4, product.PRD_LIBID4, Pro_Tabl[3], product.PRD_TYPID);
            Visibilitys(5, product.PRD_LIBID5, Pro_Tabl[4], product.PRD_TYPID);
            Visibilitys(6, product.PRD_LIBID6, Pro_Tabl[5], product.PRD_TYPID);
            Visibilitys(7, product.PRD_LIBID7, Pro_Tabl[6], product.PRD_TYPID);
            Visibilitys(8, product.PRD_LIBID8, Pro_Tabl[7], product.PRD_TYPID);
            Visibilitys(9, product.PRD_LIBID9, Pro_Tabl[8], product.PRD_TYPID);
            Visibilitys(10, product.PRD_LIBID10, Pro_Tabl[9], product.PRD_TYPID);
            Visibilitys(11, product.PRD_LIBID11, Pro_Tabl[10], product.PRD_TYPID);
            Visibilitys(12, product.PRD_LIBID12, Pro_Tabl[11], product.PRD_TYPID);

            if (taken.Val01 == null)
            {
                //if (cbo01.Visibility == Windows.UI.Xaml.Visibility.Collapsed) txt01.Text = DateTime.Now.ToString("dd/MM/yyyy") ;
                //if (cbo02.Visibility == Windows.UI.Xaml.Visibility.Collapsed) txt02.Text = DateTime.Now.ToString("dd/MM/yyyy");
                //if (cbo03.Visibility == Windows.UI.Xaml.Visibility.Collapsed) txt03.Text = DateTime.Now.ToString("HH:mm");
            }
            else
            {
                txtComment.Text = taken.Comment == null ? string.Empty : taken.Comment;
                SetValue(taken.Val01, txt01, cbo01);
                SetValue(taken.Val02, txt02, cbo02);
                SetValue(taken.Val03, txt03, cbo03);
                SetValue(taken.Val04, txt04, cbo04);
                SetValue(taken.Val05, txt05, cbo05);
                SetValue(taken.Val06, txt06, cbo06);
                SetValue(taken.Val07, txt07, cbo07);
                SetValue(taken.Val08, txt08, cbo08);
                SetValue(taken.Val09, txt09, cbo09);
                SetValue(taken.Val10, txt10, cbo10);
                SetValue(taken.Val11, txt11, cbo11);
                SetValue(taken.Val12, txt12, cbo12);
            }

            List<TakenAnalyzeViewModel> analyses = (new TakenAnalyzeViewModel()).GetAnalyzeByTakenId(CurrentTakenID);
            
            int RowLastIndex = grdSummary.RowDefinitions.Count();
            foreach (TakenAnalyzeViewModel a in analyses)
            {
                // Add the label cell to the Grid
                TextBlock lbl = new TextBlock();
                lbl.Text = a.AnalyzeLabel;
                lbl.FontSize = 14.66;
                lbl.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
                Grid.SetColumn(lbl, 0);
                Grid.SetRow(lbl, RowLastIndex);

                // Add the text cell to the Grid
                TextBox txt = new TextBox();
                txt.Tag = a.AnalyzeCode;
                txt.Text = a.AnalyzeValue == null ? "" : a.AnalyzeValue;
                txt.Margin = new Thickness(4);
                Grid.SetColumn(txt, 1);
                Grid.SetRow(txt, RowLastIndex);

                grdSummary.RowDefinitions.Add(new RowDefinition());
                grdSummary.Children.Add(lbl);
                grdSummary.Children.Add(txt);

                _TextBoxs.Add(txt);
                
                RowLastIndex++;
            }
            
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void Visibilitys(int RowNum, string ProductLabel, string ProductTable, string ProductType)
        {
            string[] prélèvement = new string[] { "Date de prélèvement", "Heure de prélèvement", "Prélevé par" };
            TextBlock[] lbls = new TextBlock[] { lbl01, lbl02, lbl03, lbl04, lbl05, lbl06, lbl07, lbl08, lbl09, lbl10, lbl11, lbl12 };
            TextBox[] txts = new TextBox[] { txt01, txt02, txt03, txt04, txt05, txt06, txt07, txt08, txt09, txt10, txt11, txt11 };
            ComboBox[] cbos = new ComboBox[] { cbo01, cbo02, cbo03, cbo04, cbo05, cbo06, cbo07, cbo08, cbo09, cbo10, cbo11, cbo12 };
            Windows.UI.Xaml.Visibility Visibility = ProductLabel =="" ? Windows.UI.Xaml.Visibility.Collapsed : Windows.UI.Xaml.Visibility.Visible;
            TextBlock lbl = lbls[RowNum - 1];
            TextBox txt = txts[RowNum - 1];
            ComboBox cbo = cbos[RowNum - 1];
            lbl.Visibility = Visibility;
            txt.Visibility = Visibility == Windows.UI.Xaml.Visibility.Visible ? ProductTable == "" ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed : Visibility;
            cbo.Visibility = Visibility == Windows.UI.Xaml.Visibility.Visible ? ProductTable == "" ? Windows.UI.Xaml.Visibility.Collapsed : Windows.UI.Xaml.Visibility.Visible : Visibility;
            
            if (prélèvement.Contains(lbl.Text))
            {
                txt.IsReadOnly = true;
                cbo.IsEnabled = false;
                txt.Visibility = Windows.UI.Xaml.Visibility.Visible;
                cbo.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                switch (lbl.Text)
                {
                    case "Heure de prélèvement":
                        txt.Text = DateTime.Now.ToString("HH:mm");
                        break;
                    case "Prélevé par":
                        txt.Text = CurrentUser;
                        break;
                    default:
                        txt.Text = DateTime.Now.ToString("dd/MM/yyyy");
                        break;
                }
            }
            
            if (cbos[RowNum - 1].Visibility == Visibility) cbos[RowNum - 1].ItemsSource = (new IDENTViewModel()).GetIdentValue(ProductTable).Select(v=> v.DisplayValue).ToList();

            if (txts[RowNum - 1].Visibility == Windows.UI.Xaml.Visibility.Visible)
            {
                string TypeID = ProductType.Substring((RowNum - 1) * 2, 2).Trim();
                if (TypeID.Equals("DS") || TypeID.Equals("D") || TypeID.Equals("H"))
                {
                    txts[RowNum - 1].Tag = TypeID.Trim();
                    txts[RowNum - 1].LostFocus += TakenSummaryPage_LostFocus;
                }
                else if (TypeID.Equals("N"))
                {
                    txts[RowNum-1].InputScope = new Windows.UI.Xaml.Input.InputScope()
                    {
                        Names = { new Windows.UI.Xaml.Input.InputScopeName() { NameValue = Windows.UI.Xaml.Input.InputScopeNameValue.NumberFullWidth }
                        }
                    };
                }

            }
        }

        async void TakenSummaryPage_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox txt =  ((TextBox)sender);
            if (!DateTimeTextBox(txt, txt.Tag.ToString(), true))
            {
                // Create the message dialog and set its content; it will get a default "Close" button since there aren't any other buttons being added
                var messageDialog = new MessageDialog(new msg().date_valide);

                // Show the message dialog and wait
                await messageDialog.ShowAsync();

                txt.Focus(Windows.UI.Xaml.FocusState.Keyboard);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            string val = string.Empty;
            var db = new SQLite.SQLiteConnection(App.DBPath);
            k_taken taken = db.Table<k_taken>().Where(t => t.taken_id == CurrentTakenID).First();

            taken.comment = txtComment.Text;
            taken.value_01 = GetValue(txt01, cbo01);

            taken.value_02 = GetValue(txt02, cbo02);

            taken.value_03 = GetValue(txt03, cbo03);

            taken.value_04 = GetValue(txt04, cbo04);

            taken.value_05 = GetValue(txt05, cbo05);

            taken.value_06 = GetValue(txt06, cbo06);

            taken.value_07 = GetValue(txt07, cbo07);

            taken.value_08 = GetValue(txt08, cbo08);

            taken.value_09 = GetValue(txt09, cbo09);

            taken.value_10 = GetValue(txt10, cbo10);

            taken.value_11 = GetValue(txt11, cbo11);

            taken.value_12 = GetValue(txt12, cbo12);
            taken.status = 3;

            db.Update(taken);

            List<k_taken_analyze> analyzes = db.Table<k_taken_analyze>().Where(a => a.taken_id == CurrentTakenID && a.to_do == true).ToList();

            foreach (TextBox txt in _TextBoxs)
            {
                k_taken_analyze an = analyzes.Where(a => a.analyze_code == txt.Tag.ToString()).First();
                an.analyze_value = txt.Text;
            }

            db.UpdateAll(analyzes);

            this.Frame.Navigate(typeof(ClientTakenPage), taken.client_taken_id);
        }

        private string GetValue( TextBox txt, ComboBox cbo)
        {
            string cboVal = cbo.SelectedValue == null ? "" : cbo.SelectedValue.ToString();
            if (txt.Visibility == Windows.UI.Xaml.Visibility.Collapsed && cbo.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
            {
                return "";
            }
            else
            {
                return txt.Visibility == Windows.UI.Xaml.Visibility.Collapsed ? cboVal : txt.Text;
            }
        }

        private void SetValue(string Val, TextBox txt, ComboBox cbo)
        {
            if (txt.Visibility != Windows.UI.Xaml.Visibility.Collapsed || cbo.Visibility != Windows.UI.Xaml.Visibility.Collapsed)
            {
                if (txt.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
                {
                    cbo.SelectedValue = Val;
                }
                else
                {
                    txt.Text = Val==null ? string.Empty : Val;
                }
            }
        }

        internal bool DateTimeTextBox(TextBox txt, string DateFormat, Boolean allowNull = false)
        {
            if (allowNull && txt.Text.Trim() == "") return true;
            try
            {
                if (DateFormat.Equals("DS") || DateFormat.Equals("D"))
                {
                    string[] arr = txt.Text.Split('/');
                    DateTime dateValue = new DateTime(int.Parse(arr[2]), int.Parse(arr[1]), int.Parse(arr[0]));
                    
                    txt.Text = dateValue.Date.ToString("dd/MM/yyyy");
                }
                else if (DateFormat.Equals("H"))
                {
                    string[] arr = txt.Text.Split(':');
                    DateTime dateValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(arr[0]), int.Parse(arr[1]), 00);

                    txt.Text = dateValue.ToString("HH:mm");
                }
                return true;
            }
            catch
            {
                return false;
            }

        }

        private void GoBack(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ClientTakenPage), App.ClientTakenId);
        }
    }
}
